import pyglet
import sys
import os

def get_exe_directory():
    """获取exe文件所在的目录"""
    # 如果程序是打包后的exe，sys.argv[0]就是exe的路径
    # 如果程序是Python脚本，sys.argv[0]就是脚本的路径
    exe_path = os.path.abspath(sys.argv[0])
    return os.path.dirname(exe_path)

def get_resource_path(relative_path: str):
    """获取资源的完整路径（在exe同级目录中）"""
    exe_dir = get_exe_directory()
    return os.path.join(exe_dir, relative_path)

def load_script():
    # 直接在exe同级目录中查找文件
    script_path = get_resource_path(R'resources\script_resources.txt')
    print(f"Loading script from: {script_path}")
    with open(script_path, 'r', encoding='UTF-8') as file:
        lines = file.readlines()
    return lines

def load_muc() -> dict[str, pyglet.image.AbstractImage]:
    d = {}
    muc_path = get_resource_path(R'resources\muc_resources.txt')
    print(f"Loading music list from: {muc_path}")
    with open(muc_path, 'r') as file:
        lines = file.readlines()
        for line in lines:
            a = line.strip().split(' ')
            name = a[0]
            # 音频文件也在exe同级目录中
            audio_path = get_resource_path('audio\\'+a[1])
            print(f"Loading audio: {audio_path}")
            muc = pyglet.media.load(audio_path)
            d[name] = muc
        return d

def load_pic() -> dict[str, pyglet.image.AbstractImage]:
    d = {}
    pic_path = get_resource_path(R'resources\pic_resources.txt')
    print(f"Loading picture list from: {pic_path}")
    with open(pic_path, 'r') as file:
        lines = file.readlines()
    for line in lines:
        a = line.strip().split(' ')
        name = a[0]
        # 图片文件也在exe同级目录中
        image_path = get_resource_path('pictures\\'+a[1])
        print(f"Loading image: {image_path}")
        img = pyglet.image.load(image_path)
        d[name] = img
    return d

def load_charactor_pic() -> dict[str, pyglet.image.AbstractImage]:
    d = {}
    char_path = get_resource_path(R'resources\charactor_resources.txt')
    print(f"Loading character list from: {char_path}")
    with open(char_path, 'r') as file:
        lines = file.readlines()
    for line in lines:
        a = line.strip().split(' ')
        name = a[0]
        # 角色图片文件也在exe同级目录中
        char_image_path = get_resource_path("charactors\\"+a[1])
        print(f"Loading character image: {char_image_path}")
        img = pyglet.image.load(char_image_path)
        d[name] = img
    return d

def output_saves(name, content):
    # 存档文件直接保存在exe同级目录中
    save_path = get_resource_path('saves\\'+name + '.txt')
    print(f"Saving to: {save_path}")
    with open(save_path, 'w') as file:
        file.write(content)
    return 1

def read_saves(name):
    # 存档文件直接从exe同级目录中读取
    save_path = get_resource_path('saves\\'+name + '.txt')
    print(f"Reading from: {save_path}")
    try:
        with open(save_path, 'r') as file:
            lines = file.readlines()
        return int(lines[0])
    except FileNotFoundError:
        return -1